package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        Map<String,Object> map = new HashMap<>();
        ApUser apUser1 = new ApUser();
        if(StringUtils.isBlank(dto.getPassword())&&StringUtils.isBlank(dto.getPhone())){
            String token = AppJwtUtil.getToken(0L);
            apUser1.setId(0);
            apUser1.setPassword("");
            apUser1.setPhone("");
            map.put("user",apUser1);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }else{
           if(StringUtils.isNotBlank(dto.getPhone())){
               LambdaQueryWrapper<ApUser> wrapper = Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone());
               ApUser apUser = apUserMapper.selectOne(wrapper);
               if(apUser==null){
                   return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
               }
               boolean checkpw = BCrypt.checkpw(dto.getPassword(), apUser.getPassword());
               if(checkpw){
                   String token = AppJwtUtil.getToken(apUser.getId().longValue());
                   apUser1.setId(apUser.getId());
                   apUser1.setPassword(apUser.getPassword());
                   apUser1.setPhone(apUser.getPhone());
                   map.put("user",apUser1);
                   map.put("token",token);
                   return ResponseResult.okResult(map);
               }else{
                   return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
               }
           }else{
               return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
           }
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
